package com.ladlee.bean.resolver;

import com.ladlee.constant.SecurityConstants;
import com.ladlee.vo.SysRole;
import com.ladlee.vo.UserVO;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: dingchang
 * @Date: 2018/12/15 11:44
 * @Description: 将请求中的Token转化UserVo
 */
@Configuration
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 1. 入参筛选
     *
     * @param methodParameter 参数集合
     * @return 是否匹配
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(UserVO.class);
    }

    /**
     *
     * @param methodParameter  入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest web相关
     * @param webDataBinderFactory 入参解析
     * @return 包装对象
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String username = request.getHeader(SecurityConstants.USER_HEADER);//从请求头里获取用户名
        String roles = request.getHeader(SecurityConstants.ROLE_HEADER);//获取角色
        if(StrUtil.isBlank(roles) || StrUtil.isBlank(username)){
            log.warn("resolveArgument error username or role is empty--------------->用户角色或者用户名为空");
            return null;
        }else{
            log.debug("resolveArgument username（用户名） :{} roles（角色）:{}", username, roles);
        }
        UserVO userVO = new UserVO();
        userVO.setUsername(username);
        List<SysRole> sysRoleList = new ArrayList<>();
        Arrays.stream(roles.split(",")).forEach(role -> {
            SysRole sysRole = new SysRole();
            sysRole.setRoleCode(role);
            sysRoleList.add(sysRole);
        });
        userVO.setRoleList(sysRoleList);
        return userVO;
    }
}
